package com.Lyoto.NetNotify.Utils;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-09-20 10:20
 * @Version
 **/
public class YmlUtil {
    public static Map yaml;

    static {
        yaml = loadYml("config.yml");
    }

    public static final String SPLIT_CHAR = ".";

    public static String getByTag(String... names) {
        if (names.length == 1) {
            return prase(names[0]);
        }
        StringBuilder builder = new StringBuilder();
        for (String s : names) {
            s = prase(s);
            builder.append(s);
        }
        return builder.toString();
    }

    @SuppressWarnings("unchecked")
    public static <T> T prase(String name) {
        T re = null;
        if (name.contains(SPLIT_CHAR)) {
            String[] split = name.split("\\" + SPLIT_CHAR);
            Map map = yaml;
            for (int i = 0; i < split.length; i++) {
                Object o = map.get(split[i]);
                if ( o instanceof Map tempMap) {
                    map = tempMap;
                    continue;
                }
                if (i == split.length -1){
                    re = (T) map.get(split[i]);
                }
            }
            return re;
        }
        return (T) yaml.get(name);
    }

    private static LinkedHashMap<String, Object> loadYml(String configName) {
        Yaml yaml = new Yaml();
        InputStream stream = YmlUtil.class.getClassLoader().getResourceAsStream(configName);
        return yaml.load(stream);
    }

    public static void main(String[] args) {
        String prase = YmlUtil.getByTag("weixin.api", "weixin.message.path.send");
        System.out.println(prase);
    }

}
